"""
Video creator module for HeyGen video generation.
Handles the overall video creation process.
"""

import sys
import os

# Add the project root directory to the Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from playwright.async_api import Page
from src.video_generator.avatar_selector import AvatarSelector
from src.video_generator.script_manager import ScriptManager
from src.video_generator.voice_selector import VoiceSelector


class VideoCreator:
    """
    Manages the video creation process in HeyGen.
    """
    
    def __init__(self):
        self.avatar_selector = AvatarSelector()
        self.script_manager = ScriptManager()
        self.voice_selector = VoiceSelector()
    
    async def create_video(self, page: Page, avatar_name: str, avatar_description: str) -> bool:
        """
        Create a video with the specified avatar and description.
        
        Args:
            page (Page): Playwright page instance
            avatar_name (str): Name of the avatar to use
            avatar_description (str): Description of the avatar for script generation
            
        Returns:
            bool: True if video creation initiated successfully, False otherwise
        """
        try:
            # Click the create button
            await page.click('iconpark-icon[name="new-video"]')
            print("Clicked Create button")
            
            # Wait for options to appear
            await page.wait_for_timeout(3000)
            
            # Try to click "Quick avatar video" option
            quick_video_option = await page.query_selector("text=Quick avatar video")
            if quick_video_option:
                # Try multiple methods to click the option
                try:
                    await quick_video_option.click()
                    print("Selected Quick avatar video using query_selector")
                except:
                    # If direct click fails, try with force option
                    await page.click("text=Quick avatar video", force=True)
                    print("Selected Quick avatar video using force click")
            else:
                print("Quick avatar video option not found")
                return False
                
            print("Quick avatar video option appeared")
            
            # Wait for the avatar selection dialog
            await page.wait_for_timeout(5000)
            
            # Select avatar
            avatar_selected = await self.avatar_selector.select_avatar(page, avatar_name)
            if not avatar_selected:
                print(f"Failed to select avatar: {avatar_name}")
                return False
            
            # Click next button
            await page.click("button:has-text('Next: Add Script')")
            print("Clicked Next: Add Script")

            
            # Wait for script section
            await page.wait_for_timeout(3000)
            
            # Add script
            script_added = await self.script_manager.add_script(page, avatar_name)
            if not script_added:
                print("Failed to add script")
                return False
            
            # Select voice
            # voice_selected = await self.voice_selector.select_voice(page, avatar_name)
            # if not voice_selected:
                # print("Failed to select voice")
                # return False
            
            # Try to click generate button
            try:
                generate_button = await page.query_selector("button:has-text('Generate video')")
                if generate_button:
                    await generate_button.click()
                    print("Clicked Generate video")
                    await page.wait_for_timeout(10000)
                    limit_button = await page.query_selector("button:has-text('Use Avatar Unlimited')")
                    if limit_button:
                        await limit_button.click()
                        print("Clicked Use Avatar Unlimited")
                    await page.await_for_timeout(10000)
                    await page.goto("https://app.heygen.com/projects")
                    await page.wait_for_timeout(50000)
                    await page.locator("iconpark-icon[name='iconpark-icon']").nth(0).click()
                    await page.wait_for_timeout(3000)
                    await page.locator("iconpark-icon[name='more-level']").nth(0).click()
                    await page.wait_for_timeout(3000)
                    await page.locator("span:has-text('Download')").click()
                    await page.wait_for_timeout(10000)
                else:
                    print("Generate video button not found")
                    return False
            except Exception as e:
                print(f"Could not click generate button: {e}")
                return False
            
            # Wait a bit for the generation to start
            await page.wait_for_timeout(5000)
            return True
            
        except Exception as e:
            print(f"Error creating video: {e}")
            return False